package com.cuit.zuke.product.util;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.UUID;

public class FileUtil {

    /**
     * 保存文件
     * @param imgFile
     * @param applicationHome
     * @return
     * @throws IOException
     */
    public static String saveFile(MultipartFile imgFile, ApplicationHome applicationHome) throws IOException {
        //获取上传的文件名
        String fileName=imgFile.getOriginalFilename();
        //获取文件后缀
        String suffixName=fileName.substring(fileName.lastIndexOf("."));
        //将UUID设置为文件名
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid+suffixName;

        String photoPath = getStaticImgPath(applicationHome);

        File file = new File(photoPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String finalPath = photoPath+File.separator+fileName;
        //上传文件
        imgFile.transferTo(new File(finalPath));

        return fileName;
    }

    /**
     * base64转码
     * @param filePath
     * @return
     */
    public static String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getStaticImgPath(ApplicationHome applicationHome){
        return applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+
                "\\src\\main\\resources\\static";
    }

}
